package com.zhang.second.day07;

import com.zhang.second.utils.ClickEvent;
import com.zhang.second.utils.ClickSource;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.co.CoFlatMapFunction;
import org.apache.flink.util.Collector;

/**
 * @title: 查询流实现
 * @author: zhang
 * @date: 2022/2/2 17:17
 */
public class Example1 {
    public static void main(String[] args) throws Exception {
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        env.setParallelism(1);

        DataStreamSource<ClickEvent> clickEventDataStreamSource = env
                .addSource(new ClickSource());

        DataStreamSource<String> queryDS = env
                .socketTextStream("localhost", 9999);

        clickEventDataStreamSource.keyBy(r -> r.url)
                .connect(queryDS)
                .flatMap(new QueryDS())
                .print();

        env.execute();
    }

    public static class QueryDS implements CoFlatMapFunction<ClickEvent, String, ClickEvent> {
        private String queryName = "";

        @Override
        public void flatMap1(ClickEvent value, Collector<ClickEvent> out) throws Exception {
            if (value.username.equals(queryName)) out.collect(value);
        }

        @Override
        public void flatMap2(String value, Collector<ClickEvent> out) throws Exception {
            queryName = value;
        }
    }
}
